export function createElem(el, option) {
  option = Object.assign({}, option);
  el = document.createElement(el);
  let children = option.children;
  delete option.children;
  if (!Array.isArray(children)) {
    children = [children];
  }
  children.forEach((item) => {
    if (item && item.nodeType === 1) {
      el.appendChild(item);
    } else if (item !== undefined && item !== null) {
      el.innerHTML += String(item);
    }
  });
  for (const key in option) {
    el.setAttribute(key, option[key]);
  }
  return el;
}

export function getTargetUpperElem(el, predicate) {
  if (typeof predicate === 'function') {
    while (el && el.nodeType === 1) {
      if (predicate(el)) {
        return el;
      }
      el = el.parentElement;
    }
  }
}

export function getElemOffsetTop(el) {
  let top = 0;
  while (el && el.nodeType === 1 && el !== document.body) {
    top += el.offsetTop;
    el = el.parentNode;
  }
  return top;
}

export function setFavicon(icon) {
  let link = document.querySelector('link[rel="icon"]');
  if (!link || link.nodeType !== 1) {
    link = document.createElement('link');
    link.rel = 'icon';
    document.head.appendChild(link);
  }
  link.href = icon;
}

export const setDocumentTitle = function (title) {
  document.title = title;
};
